package com.jmb.api.common.utils;

import com.alibaba.fastjson2.JSON;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jmb.api.common.exception.ParseException;
import lombok.extern.slf4j.Slf4j;
import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ParseUtil {

    private static final Configuration JSON_PATH_CONFIG =
            Configuration.builder().options(Option.ALWAYS_RETURN_LIST).build();
    /**
     * xpath解析
     *
     * @param xmlText  xml string
     * @param xpath xpath
     * @return 提取表达式
     * @throws ParseException 解析异常
     */
    // xpath解析
    public static  String parseXml(String xmlText,String xpath){
        log.info("-------------------------------------------开始XML解析流程------------------------------------");
        try {
            JXDocument document = JXDocument.create(xmlText);
            List<JXNode> nodes = document.selN(xpath);
            ArrayList<String> result = new ArrayList<>();
            for (JXNode node : nodes){
                result.add(node.asString());
            }
            return JSON.toJSONString( result);
        }catch (Exception e){
            String safeXmlPreview = xmlText.length() > 100 ? xmlText.substring(0, 100) + "...." : xmlText;
            log.error("XML解析失败，XML预览：{}", safeXmlPreview);
            String msg = String.format("xpath 解析错误！ xml/html preview = [%s]，xpath= [%s], error-msg = [%s]",
                    safeXmlPreview, xpath, e.getMessage());
            throw new ParseException(msg);
        }
    }
    // 解析http状态码
    /**
     * 解析http状态码
     *
     * @param entity ResponseEntity
     * @return http 状态码
     */
    public static Integer parseHttpCode(ResponseEntity entity){
        return entity.getStatusCode().value();
    }
    // 解析请求头

    /**
     * 解析请求头
     *
     * @param entity ResponseEntity
     * @param headerName headerName
     * @return 请求头
     * @throws ParseException 解析异常
     */
    public static String parseHttpHeaders(ResponseEntity entity,String headerName){
        HttpHeaders headers = entity.getHeaders();
        if (!headers.containsKey(headerName)){
            String msg = String.format("响应头不存在！响应头名称：[%s]", headerName);
            log.error(msg);
            throw new ParseException(msg);
        }
        List<String> values = headers.get(headerName);
        return JSON.toJSONString(values);
    }
    // 解析响应体,解析json
    /**
     * 解析json
     *
     * @param jsonText json string
     * @param jsonPath json path
     * @return 提取结果
     */
    public static String parseJson(String jsonText,String jsonPath){
        log.info("-------------------------------------------开始JSON解析流程------------------------------------");
        try {
           return JSON.toJSONString(JsonPath.using(JSON_PATH_CONFIG).parse(jsonText).read(jsonPath));
        }catch (Exception e){
            String safeJsonPreview = jsonText.length() > 100 ? jsonText.substring(0, 100) + "...." : jsonText;
            log.error("JSON解析失败，JSON预览：{}", safeJsonPreview);
            String msg = String.format("json 解析错误！ json preview = [%s]，jsonPath= [%s], error-msg = [%s]",
                    safeJsonPreview, jsonPath, e.getMessage());
            throw new ParseException(msg);

        }

    }
}
